# coding: UTF-8


import os
import sys

# 将project目录加入sys.path

from utils import filters
from utils.account import get_current_user

project_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
if project_path not in sys.path:
    sys.path.insert(0, project_path)

from flask import Flask, request, url_for, g, session
from flask_wtf.csrf import CsrfProtect

from config import load_config


# convert python's encoding to utf8
reload(sys)
sys.setdefaultencoding('utf8')

csrf = CsrfProtect()


def create_app():
    """创建Flask app"""
    app = Flask(__name__)


    # Load config
    config = load_config()
    app.config.from_object(config)

    # CSRF protect
    csrf.init_app(app)
    # if app.debug:
    #     DebugToolbarExtension(app)

    # 注册组件

    register_routes(app)
    register_jinja(app)

    register_logger(app)

    # before every request
    @app.before_request
    def before_request():
        """Do something before request"""
        if 'User' not in session:
            session['User'] = None

    return app


def register_jinja(app):
    """注册filter，模板全局变量和全局函数"""

    app.jinja_env.filters['timesince'] = filters.timesince
    app.jinja_env.filters['get_page_name'] = filters.get_page_name
    app.jinja_env.filters['striptags'] = filters.striptags
    app.jinja_env.filters['get_num'] = filters.get_num
    from jinja2 import Markup

    # inject vars into template context
    @app.context_processor
    def inject_vars():

        return dict(
            user=session.get('User', {})
        )

    def url_for_other_page(page, key='page', params=None):
        """Generate url for pagination"""
        view_args = request.view_args.copy()
        args = request.args.copy().to_dict()
        combined_args = dict(view_args.items() + args.items())
        combined_args[key] = page
        if params:
            combined_args.update(params)
        return url_for(request.endpoint, **combined_args)

    def set_url_param(params):
        """Set param in url"""
        view_args = request.view_args.copy()
        args = request.args.copy().to_dict()
        combined_args = dict(view_args.items() + args.items())
        if params:
            combined_args.update(params)
        return url_for(request.endpoint, **combined_args)

    def register_vars(dict):
        """生成用于后台传值的meta标签"""
        meta = ''
        for key, value in dict.items():
            meta += '<meta type=pv name="%s" content="%s" />' % (key, value)
        return Markup(meta)

    from random import randint

    def random_num_str(length):
        """生成指定长度的随机数字字符串"""
        return ''.join(["%s" % randint(0, 9) for num in range(0, length)])

    app.jinja_env.globals['url_for_other_page'] = url_for_other_page
    app.jinja_env.globals['set_url_param'] = set_url_param
    app.jinja_env.globals['random_num_str'] = random_num_str
    app.jinja_env.globals['register_vars'] = register_vars

    @app.template_filter('get_name')
    def get_name(template_reference):
        template_name = template_reference._TemplateReference__context.name
        return "page-%s" % template_name.replace('/', '-').split('.')[0]


def register_logger(app):
    """日志记录"""
    if False:
        import logging
        from logging.handlers import RotatingFileHandler

        # 创建一个logger
        logger = logging.getLogger()
        logger.setLevel(logging.INFO)

        # 创建一个handler，用于写入日志文件
        rfh = RotatingFileHandler('%s/web.log' % app.config.get('PROJECT_PATH'), 'a',
                                  1 * 1024 * 1024, 10)
        rfh.setLevel(logging.INFO)

        # 定义handler的输出格式
        formatter = logging.Formatter(
            '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')
        rfh.setFormatter(formatter)

        # 给logger添加handler
        logger.addHandler(rfh)
        logger.info('start logging...')
        for item in sys.path:
            logger.info(item)


def register_routes(app):
    """注册路由"""

    from app.base.views import base_page
    app.register_blueprint(base_page, url_prefix='')

    # ----end----
